package com.itheima.service.mongo.impl;

import cn.hutool.core.collection.CollUtil;
import com.itheima.domain.mongo.RecommendUser;
import com.itheima.service.mongo.RecommendUserService;
import com.itheima.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class RecommendUserServiceImpl implements RecommendUserService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public RecommendUser findTodayBest(Long toUserId) {
        //1.查询对象(userId,排序,分页)
        Query query = new Query(Criteria.where("toUserId").is(toUserId))
                .with(Sort.by(Sort.Order.desc("score")))
                .skip(0).limit(1);

        //2.查询推荐用户表,返回数据
        return mongoTemplate.findOne(query,RecommendUser.class);
    }

    @Override
    public PageBeanVo findByPage(Long toUserId, Integer pageNum, Integer pageSize) {
        //1.创建条件对象(用户id)
        Query query = new Query(Criteria.where("toUserId").is(toUserId));

        //2.查询推荐用户表获取总条数
        long count = mongoTemplate.count(query, RecommendUser.class);

        //3.给条件对象追加参数(分页和排序)
        query.with(Sort.by(Sort.Order.desc("score")))
                .skip((pageNum-1)*pageSize+1).limit(pageSize);

        //4.查询当前页的数据集合
        List<RecommendUser> list = mongoTemplate.find(query, RecommendUser.class);

        /*
        推荐的用户只有1个
        总记录数就是1,但是查询list大小为0
        最好封装pageBeanVo的时候,对count进行重新计算
         */
        if (CollUtil.isNotEmpty(list)&&list.size()==0) {
            count=0;
        }else if(list.size()>1){
            count=count-1;
        }

        //5.封装pageBeanVo且返回
        return new PageBeanVo(pageNum,pageSize,count,list);
    }

    @Override
    public RecommendUser findPersonalInfo(Long toUserId, Long recommendUserId) {
        //1.创建条件对象 俩用户id
        Query query = new Query(Criteria.where("toUserId").is(toUserId).and("userId").is(recommendUserId));
        //2.查询推荐用户表,最多只有一个数据,返回
        return mongoTemplate.findOne(query,RecommendUser.class);
    }


    /**
     * 查询推荐用户
     * @param toUserId
     * @return
     */
    @Override
    public List<RecommendUser> findUser(Long toUserId) {
        Query query = new Query(
                Criteria.where("toUserId").is(toUserId)
        );

        return mongoTemplate.find(query,RecommendUser.class);
    }



    /**
     * 删除推荐用户
     * @param userId
     */
    @Override
    public void delete(Long userId) {
        Query query = new Query(
                Criteria.where("userId").is(userId)
        );
        mongoTemplate.remove(query,RecommendUser.class);
    }
}
